package com.softeem.util;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Component
public class FileUtil {

    private Path fileStorageLocation; // 文件在本地存储的地址

    public FileUtil( @Value("${file.upload.path}") String path) {
        this.fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
        try {
            //创建目录
            Files.createDirectories(this.fileStorageLocation);
        } catch (IOException e) {
            throw new RuntimeException("目录创建失败!", e);
        }
    }

    public  String storeFile(MultipartFile file) {
        // 普通文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            // 检查文件名是否包含特殊字符
            if(fileName.contains("..")) {
                throw new RuntimeException("你的文件名包含特殊字符 " + fileName);
            }
            // 把文件存储在磁盘上
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            //文件拷贝
            // 参数1：附件   参数2：目标文件  REPLACE_EXISTING 若存在则替换
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new RuntimeException("不能够存储 " + fileName + ". 请重新再试!", ex);
        }
    }

    //下载
    /**
     * 读系统中的文件
     * @param fileName  下载的文件名
     * @return  字节方式存储附件
     */
    public   Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new RuntimeException(fileName+"文件找不到");
            }
        } catch (MalformedURLException ex) {
            throw new RuntimeException(fileName+"文件找不到",ex);
        }
    }
}
